package com.chatbot.domain.zsxq.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chatbot.domain.zsxq.model.aggregates.UnAnsweredQuestionAggregates;
import com.chatbot.domain.zsxq.model.req.answer.AnswerReq;
import com.chatbot.domain.zsxq.model.req.answer.AnswerReqData;
import com.chatbot.domain.zsxq.model.res.answer.AnswerRes;
import com.chatbot.domain.zsxq.model.vo.Topics;
import com.chatbot.domain.zsxq.service.IZsxqApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static org.apache.http.HttpStatus.SC_OK;

@Slf4j
@Service
public class ZsxqApiImpl implements IZsxqApi {
    @Override
    public UnAnsweredQuestionAggregates queryUnAnsweredQuestionsTopicId(String groupId, String cookie) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpGet get = new HttpGet("https://api.zsxq.com/v2/groups/" + groupId + "/topics?scope=all&count=10");

        get.addHeader("cookie", cookie);
        get.addHeader("Content-Type", "application/json, text/plain, */*");

        CloseableHttpResponse response = httpClient.execute(get);
        if (response.getStatusLine().getStatusCode() == SC_OK) {
            String jsonStr = EntityUtils.toString(response.getEntity());
            log.info("拉取提问数据。groupId：{} jsonStr：{}", groupId, jsonStr);
            UnAnsweredQuestionAggregates result = JSON.parseObject(jsonStr, UnAnsweredQuestionAggregates.class);
            if (!result.getSucceeded()) {
                return null;
            }
//            log.info("拉取提问数据。过滤前问题数量：{}", result.getResp_data().getTopics().size());
            List<Topics> questions = result.getResp_data().getTopics().stream()
                    //只过滤自己id的问题
                    .filter(o -> Objects.equals(o.getTalk().getOwner().getUser_id(), "818842854811822"))
                    //.filter(o-> o.getComments_count()>0)//过滤评论数为0的问题
                    .collect(Collectors.toList());
            result.getResp_data().setTopics(questions);
            log.info("拉取提问数据。过滤后问题数量：{}", questions.size());
            return result;
        } else {
            throw new RuntimeException("queryUnAnsweredQuestionsTopicId Err Code is " + response.getStatusLine().getStatusCode());
        }
    }

    @Override
    public boolean answer(String groupId, String cookie, String topicId, String text, List<String> imageIds, List<String> mentionedUserIds) throws IOException {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost post = new HttpPost("https://api.zsxq.com/v2/topics/" + topicId + "/comments");

        post.addHeader("cookie", cookie);
        post.addHeader("Content-Type", "application/json");
        //模拟浏览器，防风控检测
        post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");

        //uid:818842854811822
//        String paramJson = "{\n" +
//                "  \"req_data\": {\n" +
//                "    \"text\": \"我不会!!\\n\",\n" +
//                "    \"image_ids\": [],\n" +
//                "    \"mentioned_user_ids\": []\n" +
//                "  }\n" +
//                "}";

        AnswerReq answerReq = new AnswerReq(new AnswerReqData(text, imageIds, mentionedUserIds));
        String paramJson = JSONObject.toJSONString(answerReq);

        StringEntity stringEntity = new StringEntity(paramJson, ContentType.create("text/json", "UTF-8"));
        post.setEntity(stringEntity);

        CloseableHttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() == SC_OK) {
            String jsonStr = EntityUtils.toString(response.getEntity());
            log.info("回答问题结果。groupId：{} topicId：{} jsonStr：{}", groupId, topicId, jsonStr);
            AnswerRes answerRes = JSON.parseObject(jsonStr, AnswerRes.class);
            return answerRes.isSucceeded();
        } else {
            throw new RuntimeException("answer Err Code is " + response.getStatusLine().getStatusCode());
        }
    }
}
